package com.yk.airline.dao.analysisdata.impl;

import com.yk.airline.dao.analysisdata.api.IAnalysisDataDao;
import com.yk.airline.dao.common.impl.CommonDaoImpl;
import com.yk.airline.model.AnalysisDataModel;
import com.yk.airline.model.CaptureMarkModel;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.*;

/**
 * Project Name:airlinecrawler
 * File Name:AnalysisDataDaoImpl
 * Package Name:com.yk.airline.dao.analysisdatadao.impl
 * Date:2018/1/31 14:32
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2018, 重庆云凯科技有限公司 All Rights Reserved.
 */
@Repository("analysisDataDao")
public class AnalysisDataDaoImpl extends CommonDaoImpl<AnalysisDataModel> implements IAnalysisDataDao {

    @Override
    public List<AnalysisDataModel> findAll() {
        String hql = "from AnalysisDataModel";
        return super.comSearchDao.findByParams(hql,null);
    }

    @Override
    public int findTotalCount() {
        String hql = "select count(id) from AnalysisDataModel";
        return super.comSearchDao.findCount(hql,null);
    }

    @Override
    public List<AnalysisDataModel> queryByCondition(CaptureMarkModel captureMarkModel , String website, List<String> airCompanies) {
        String hql = "from AnalysisDataModel as model where  model.captureMarkByCaptureTime =:captureMarkByCaptureTime and model.website =:website";
        Map<String,Object> params = new HashMap<>();//参数集
        HashSet<String> conditions=new HashSet<>();//拼接hql的条件集
        int i = 0; //区别参数名称
        for(String airCompany:airCompanies){
            conditions.add("model.flightNumber like :airCompany"+i);
            params.put("airCompany"+i, "%"+airCompany+"%");
            i++;
        }
        if(!conditions.isEmpty()){
            hql+=" and "+getOrCondition(conditions);
        }

        params.put("captureMarkByCaptureTime",captureMarkModel);
        params.put("website",website);

        System.out.println(hql);


        return super.comSearchDao.findByParams(hql,params);
    }

    /**
     * 拼接hql语句
     * @param conditions
     * @return
     */
    private String getOrCondition(HashSet<String> conditions) {
        String oneCondition="";
        if(conditions.isEmpty())
            return oneCondition;
        Iterator<String> iterator=conditions.iterator();
        while (iterator.hasNext()){
            String condition=iterator.next();
            if(!condition.isEmpty()){
                oneCondition+=condition;
                if(iterator.hasNext())
                    oneCondition+=" or ";
            }
        }
        if(conditions.size()>1)
            oneCondition="("+oneCondition+")";
        return oneCondition;
    }
}
